package top.lrshuai.websocket.ws.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lrshuai.websocket.user.entity.User;
import top.lrshuai.websocket.user.service.IUserService;
import top.lrshuai.websocket.ws.entity.WebSocketDTO;
import top.lrshuai.websocket.ws.utils.MessageSender;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 如果你添加的不是单例Handler，你加不加@Sharable没有任何区别
 * 如果你添加的是单例Handler，只要它会被添加到多个channel的pipeline，那就必须加上@Sharable
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class DataChannelHandler extends BaseChannelHandler {

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private IUserService userService;

    public void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) {
        Channel channel = channelHandlerContext.channel();
        System.out.println("datachannel="+msg.text());
        if(LocalDateTime.now().getMinute()%2==0){
//            Map<String,Object> map = new HashMap<>();
//            map.put("name","rstyro");
//            map.put("date",LocalDateTime.now());
//            map.put("age",25);
            List<User> list = userService.list(new LambdaQueryWrapper<User>());
            messageSender.sendAllMessage(WebSocketDTO.data(list));
            log.info("群发成功");
        }

    }
}
